<?php

namespace app\admin\controller\media;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Cache;

/**
 * 替换剧集
 *
 * @icon fa fa-circle-o
 */
class Replace extends Backend
{

    /**
     * Replace模型对象
     * @var \app\admin\model\media\Replace
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\media\Replace;
        $this->view->assign("statusList", $this->model->getStatusList());

        // 接收传来的参数
        $media_replace_id = input('media_replace_id/d',0);
        $this->assignconfig('media_replace_id',$media_replace_id);
        $this->view->assign("media_replace_id", $media_replace_id);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
     
      /**
     * 批量更新
     *
     * @param $ids
     * @return void
     */
    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
        foreach($list as $key => $val){
            $replace_media_list[] = array(
                "old" => $val['old_media_id'],
                "new" => $val['new_media_id'],
            );
            $drama_id = $val['drama_id'];
        }

        //提审
        $access_token = $this->get_access_token();
        $url = 'https://api.weixin.qq.com/wxa/sec/vod/submitreplacedramamedias?access_token='.$access_token;
        
        $data = array(
            "drama_id" => $drama_id,
            "replace_media_list" => $replace_media_list,
        );
        $result = json_decode($this->json_post($url,$data),true);
        if($result['errcode'] != 0){
            $values = array(
                "status" => 3
            );
            
        }else{
            $values = array(
                "status" => 2
            );
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }
     
    /**
     * 提审
     *
     * @return string
     * @throws \think\Exception
     */
    public function submitreplacedramamedias()
    {
         // 接收传来的参数进行限定条件
         $media_replace_id = input('media_replace_id');
         if(empty($media_replace_id)){
            $this->error("参数有误");
         }
         $media_replace = DB::name("media_replace")->where("id",$media_replace_id)->find();
         if($media_replace['status'] != 1 && $media_replace['status'] != 3){
            $this->error("状态有误");
         }
         
        //提审
        $access_token = $this->get_access_token();
        $url = 'https://api.weixin.qq.com/wxa/sec/vod/submitreplacedramamedias?access_token='.$access_token;
        $data = array(
            "drama_id" => $media_replace['drama_id'],
            "replace_media_list" => array(array(
                    "old" => $media_replace['old_media_id'],
                    "new" => $media_replace['new_media_id'],
                )
            ),
        );
        //查询
        // $access_token = $this->get_access_token();
        // $url = 'https://api.weixin.qq.com/wxa/sec/vod/getmedia?access_token='.$access_token;
        // $data = array(
        //     "media_id" => $params['new_media_id'],
        // );

        //审核
        // $access_token = $this->get_access_token();
        // $url = 'https://api.weixin.qq.com/wxa/sec/vod/replacedramamedia?access_token='.$access_token;
        // $data = array(
        //     "drama_id" => $params['drama_id'],
        //     "old_media_id" => $params['old_media_id'],
        //     "new_media_id" => $params['new_media_id'],
        // );
        //这里要把传递的参数给转成json，不然小程序接口会报数据类型错误。
        $result = json_decode($this->json_post($url,$data),true);
        if($result['errcode'] != 0){
            DB::name("media_replace")->where("id",$media_replace_id)->update(array("status"=>3));
            $this->error($result['errmsg']);
        }else{
            DB::name("media_replace")->where("id",$media_replace_id)->update(array("status"=>2));
            $this->success($result['errmsg']);
        }
    }

    /**
     * 查询
     *
     * @return string
     * @throws \think\Exception
     */
    public function getmedia()
    {
         // 接收传来的参数进行限定条件
         $media_replace_id = input('media_replace_id');
         if(empty($media_replace_id)){
            $this->error("参数有误");
         }
         $media_replace = DB::name("media_replace")->where("id",$media_replace_id)->find();
         if($media_replace['status'] != 2){
            $this->error("状态有误");
         }
         
        //查询
        $access_token = $this->get_access_token();
        $url = 'https://api.weixin.qq.com/wxa/sec/vod/getmedia?access_token='.$access_token;
        $data = array(
            "media_id" => $media_replace['new_media_id'],
        );

        //这里要把传递的参数给转成json，不然小程序接口会报数据类型错误。
        $result = json_decode($this->json_post($url,$data),true);

        if($result['errcode'] != 0){
            $this->error($result['errmsg']);
        }else{
            $media_info = $result['media_info'];
            if(isset($media_info['audit_detail'])){
                $status = $media_info['audit_detail']['status'];
                if($status == 1){
                    $this->error("审核中");
                }elseif($status == 2){
                    DB::name("media_replace")->where("id",$media_replace_id)->update(array("status"=>5));
                    $this->error("审核失败");
                }elseif($status == 3){
                    DB::name("media_replace")->where("id",$media_replace_id)->update(array("status"=>4));
                    $this->success("审核成功");
                }
            }else{
                $this->error("审核中");
            }
            
            
        }
    }

    /**
     * 审核
     *
     * @return string
     * @throws \think\Exception
     */
    public function replacedramamedia()
    {
         // 接收传来的参数进行限定条件
         $media_replace_id = input('media_replace_id');
         if(empty($media_replace_id)){
            $this->error("参数有误");
         }
         $media_replace = DB::name("media_replace")->where("id",$media_replace_id)->find();
         if($media_replace['status'] != 4){
            $this->error("状态有误");
         }

        //审核
        $access_token = $this->get_access_token();
        $url = 'https://api.weixin.qq.com/wxa/sec/vod/replacedramamedia?access_token='.$access_token;
        $data = array(
            "drama_id" => $media_replace['drama_id'],
            "old_media_id" => $media_replace['old_media_id'],
            "new_media_id" => $media_replace['new_media_id'],
        );
        //这里要把传递的参数给转成json，不然小程序接口会报数据类型错误。
        $result = json_decode($this->json_post($url,$data),true);

        if($result['errcode'] != 0){
            DB::name("media_replace")->where("id",$media_replace_id)->update(array("status"=>7));
            $this->error($result['errmsg']);
        }else{
            DB::name("media_replace")->where("id",$media_replace_id)->update(array("status"=>6));
            $this->success($result['errmsg']);
        }
    }

    
    //获取小程序二维码的token
    public function get_access_token()
    {
        //先判断缓存里面的access_token过期了没有
        // if(Cache::get('access_token')){
        //     //没过期直接拿出来用
        //     $a = Cache::get('access_token');
        //     return $a;
        // }else{
            //过期了就重新获取
            $appid = 'wxbae1b3248b60e1d8';
            $secret = 'b3df3f25537d5c1cdd9ac67e47b7391c';
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            
            //请求接口，获取accesstoken
            $user_obj = $this->curlHttp($url);
            //然后将accesstoken存入缓存里面，官方过期时间7200秒，缓存里面可以过期的早一点，自己把控
            Cache::set('access_token',$user_obj['access_token'],7100);

            return Cache::get('access_token');
     //   }
    }
    function curlHttp($url)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        return json_decode($output, true);
    }

     /**
     * 发送post请求
     */
    function json_post($url, $data = [])
    {
        //$data=http_build_query($data);
        //$data=json_encode($data);
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data,256);
        }
        // print_r($data);exit;
        curl_setopt($curl, CURLOPT_POST, 1);
        // var_dump($data);exit;
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json;',
            // 'Content-Length:' . strlen($data),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return $res;

    }
}
